<?php
declare(strict_types=1);

namespace LnkAdmin\controller\dict;

use LnkAdmin\controller\traits\Crud;
use think\Request;
use LnkAdmin\controller\Backend;
use LnkAdmin\model\dict\DictDataModel;
use think\facade\Db;
use think\Response;

class DictData extends Backend
{
    use Crud;
    protected function initialize()
    {
        $this->model = new DictDataModel;
    }

    /**
     * 查看
     *
     * @return Response
     */
    public function index(Request $request): Response
    {
        $params = $request->only(['type_id'=>'','code'=>'','value'=>'']);
        if (!empty($request->param('page_size'))) {       // 使用分页
           
            $list = $this->model->where('type_id',$params['type_id'])
            // ->when($params['label'],function($query) use($params){
            //     $query->where('label','like',`%{$params['label']}%`);
            // })
            // ->when($params['value'],function($query) use($params){
            //     $query->where('value',$params['value']);
            // })
            ->paginate($request->param('page_size\d', 10));
        } else {
            $list = $this->model
            ->when($params['code'],function($query) use($params){
                $query->where('code',$params['code']);
            })->select();               // 查询全部
        }

        return success('获取成功', $list);
    }

     /**
     * 添加
     *
     * @return \think\Response
     */
    public function save(Request $request)
    {
        if (!empty($this->onlyParams)) {                        // 参数过滤
            $params = $request->only($this->onlyParams);
        } else {                                                // 接受全部参数
            $params = $request->param();
        }
        $this->svalidate($params, '.add');

        $result = Db::transaction(function () use ($params) {
            return $this->model->save($params);
        });
        if ($result) {
            return success('保存成功', $this->model);
        }
        return error('保存失败');
    }

    /**
     * 编辑(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        if (!empty($this->onlyParams)) {                        // 参数过滤
            $params = $request->only($this->onlyParams);
        } else {                                                // 接受全部参数
            $params = $request->param();
        }

        $pk = $this->model->getPk();

        $result = Db::transaction(function () use ($id, $params, $pk) {
            $count = 0;
            foreach ($this->model->whereIn($pk, $id)->cursor() as $row) {
                $params[$pk] = $row->$pk;
                $this->svalidate($params);
                $count += $row->save($params);
            }
            return $count;
        });

        if ($result) {
            return success('更新成功', $result);
        } else {
            return error('更新失败');
        }
    }
}
